<template>
    <div class="personal-container">
        <!-- 顶部导航 -->
        <el-header class="header">
            <div class="header-content">
                <div class="logo" @click="router.push('/user/home')">
                    <img src="@/assets/img/logo.png" alt="logo" class="logo-img"/>
                    <span class="company-name">亿星航梦科技招聘</span>
                </div>
            </div>
        </el-header>

        <div class="main-content">
            <el-row :gutter="20">
                <!-- 左侧个人信息卡片 -->
                <el-col :span="6">
                    <el-card class="user-card">
                        <div class="user-info">
                            <el-avatar 
                                :size="100" 
                                :src="userInfo.userPic"
                            >{{ userInfo.username?.charAt(0) }}</el-avatar>
                            <h3>{{ userInfo.username }}</h3>
                            <p class="email">{{ userInfo.email }}</p>
                        </div>
                        <el-divider />
                        <div class="menu-list">
                            <div 
                                v-for="(item, index) in menuItems" 
                                :key="index"
                                :class="['menu-item', activeMenu === index ? 'active' : '']"
                                @click="activeMenu = index"
                            >
                                <el-icon>
                                    <component :is="item.icon" />
                                </el-icon>
                                <span>{{ item.label }}</span>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <!-- 右侧内容区 -->
                <el-col :span="18">
                    <!-- 基本信息 -->
                    <el-card v-show="activeMenu === 0">
                        <template #header>
                            <div class="card-header">
                                <span>基本信息</span>
                                <el-button type="primary" @click="handleEdit">编辑</el-button>
                            </div>
                        </template>
                        <el-form 
                            ref="userFormRef"
                            :model="userForm"
                            :disabled="!isEditing"
                            label-width="100px"
                        >
                            <el-form-item label="用户名">
                                <el-input v-model="userForm.username" />
                            </el-form-item>
                            <el-form-item label="姓名">
                                <el-input v-model="userForm.name" />
                            </el-form-item>
                            <el-form-item label="性别">
                                <el-input v-model="userForm.gender" />
                            </el-form-item>
                            <el-form-item label="年龄">
                                <el-input v-model="userForm.age" />
                            </el-form-item>
                            <el-form-item label="地址">
                                <el-input v-model="userForm.address" />
                            </el-form-item>
                            <el-form-item label="邮箱">
                                <el-input v-model="userForm.email" />
                            </el-form-item>
                            <el-form-item label="手机号">
                                <el-input v-model="userForm.phone" />
                            </el-form-item>
                            <el-form-item label="头像">
                                <el-upload
                                    class="avatar-uploader"
                                    action="http://localhost:8888/files/upload"
                                    :show-file-list="false"
                                    :disabled="!isEditing"
                                    :before-upload="beforeAvatarUpload"
                                    :on-success="handleAvatarSuccess"
                                >
                                    <img 
                                        v-if="userForm.userPic" 
                                        :src="userForm.userPic"
                                        class="avatar"
                                   
                                    />
                                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                                </el-upload>
                            </el-form-item>
                            <el-form-item v-if="isEditing">
                                <el-button type="primary" @click="saveUserInfo">保存</el-button>
                                <el-button @click="cancelEdit">取消</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>

                  

                    <!-- 投递记录 -->
                    <el-card v-show="activeMenu === 1">
                        <template #header>
                            <div class="card-header">
                                <span>投递记录</span>
                            </div>
                        </template>
                        <el-table :data="applicationList" style="width: 100%">
                            <el-table-column prop="intention" label="职位名称" />
                            <el-table-column prop="isApproved" label="状态">
                                <template #default="{ row }">
                                    <el-tag :type="getStatusType(row.isApproved)">
                                        {{ getStatusText(row.isApproved) }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="submitTime" label="投递时间">
                                <template #default="{ row }">
                                    {{ formatDateTime(row.submitTime) }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                        <!-- 面试结果 -->
                        <el-card v-show="activeMenu === 2">
                        <template #header>
                            <div class="card-header">
                                <span>面试结果</span>
                            </div>
                        </template>
                        <el-table :data="interviewList" style="width: 100%">
                            <el-table-column prop="candidateName" label="姓名" />
                            <el-table-column prop="positionName" label="面试岗位" />
                            <el-table-column prop="status" label="状态">
                                <template #default="{ row }">
                                    <el-tag :type="getInterviewStatusType(row.status)">
                                        {{ getInterviewStatusText(row.status) }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="submitTime" label="面试时间">
                                <template #default="{ row }">
                                    {{ formatDateTime(row.interviewTime) }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                    <!-- 账号安全 -->
                    <el-card v-show="activeMenu === 3">
                        <template #header>
                            <div class="card-header">
                                <span>账号安全</span>
                            </div>
                        </template>
                        <div class="security-list">
                            <div class="security-item">
                                <div class="security-info">
                                    <h4>登录密码</h4>
                                    <p>建议您定期更换密码，设置安全性高的密码可以使账号更安全</p>
                                </div>
                                <el-button @click="changePassword">修改</el-button>
                            </div>
                            <el-divider />
                            <div class="security-item">
                                <div class="security-info">
                                    <h4>绑定手机</h4>
                                    <p>已绑定：{{ userForm.phone }}</p>
                                </div>
                                <el-button @click="changePhone">修改</el-button>
                            </div>
                            <el-divider />
                            <div class="security-item">
                                <div class="security-info">
                                    <h4>绑定邮箱</h4>
                                    <p>已绑定：{{ userForm.email }}</p>
                                </div>
                                <el-button @click="changeEmail">修改</el-button>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Document, List, Lock, Plus } from '@element-plus/icons-vue'
import { getUserInfo, updateUserInfo,getResumeInfo,getInterviewInfo } from '@/api/user/user'
import { deleteResume } from '@/api/resume'


const router = useRouter()
const activeMenu = ref(0)
const isEditing = ref(false)
const userInfo = ref({})
const interviewList = ref([])
const applicationList = ref([])
const userId=JSON.parse(localStorage.getItem("userInfo")).user.userId
const menuItems = [
    { label: '基本信息', icon: 'User' },
    { label: '投递记录', icon: 'List' },
    { label: '面试结果', icon: 'Checked' },
    { label: '账号安全', icon: 'Lock' }
]

const userForm = ref({
    username: '',
    name:'',
    email: '',
    phone: '',
    userPic: ''
})

// 加载用户信息
const loadUserInfo = async () => {
    try {
        const res = await getUserInfo(userId)
        console.log('用户信息：', res)
        if (res.code === 200) {
            userInfo.value=res.data
          
            userForm.value = {
                userId: res.data.userId,
                name: res.data.name,
                username: res.data.username,
                gender:res.data.gender,
                age:res.data.age,
                address:res.data.address,
                email: res.data.email,
                phone: res.data.phone,
                userPic:res.data.userPic
            }
        }
    } catch (error) {
        console.error('获取用户信息失败：', error)
        ElMessage.error('获取用户信息失败')
    }
}
const loadApplication = async () => {
    try{
        const res= await getResumeInfo(userId)
        console.log(res)
        if(res.code===200){
            applicationList.value=res.data
            console.log(applicationList.value)
        }
    }catch(error){
        console.error('获取投递信息失败：', error)
        ElMessage.error('获取投递信息失败')
    }
}

const loadInterviews = async () => {
    try{
        const res= await getInterviewInfo(userId)
        console.log(res)
        if(res.code===200){
            interviewList.value=res.data
            console.log(interviewList.value)
        }
    }catch(error){
        console.error('获取面试结果信息失败：', error)
        ElMessage.error('获取面试结果信息失败')
    }
}
// 处理编辑
const handleEdit = () => {
    isEditing.value = true
}

const cancelEdit = () => {
    isEditing.value = false
    Object.assign(userForm.value, userInfo.value)
}

// 保存用户信息
const saveUserInfo = async () => {
    try {
        const res = await updateUserInfo(userForm.value)
        if (res.code === 200) {
            ElMessage.success('保存成功')
            isEditing.value = false
            await loadUserInfo()
        }
    } catch (error) {
        console.error('保存失败：', error)
        ElMessage.error('保存失败')
    }
}


// 上传成功的处理
const handleAvatarSuccess = async (res) => {
    try {
        console.log('上传响应：', res)
        if (res.code === 200) {
            userForm.value.userPic = res.data
            userInfo.value.userPic = res.data  
            
            // 更新用户信息到后端
            const updateRes = await updateUserInfo({
                ...userForm.value,
                userId: userId,
            })
            
            if (updateRes.code === 200) {
                ElMessage.success('头像更新成功')
                await loadUserInfo()  // 重新加载用户信息
            } else {
                ElMessage.error(updateRes.message || '头像信息保存失败')
            }
        } else {
            ElMessage.error(res.message || '上传失败')
        }
    } catch (error) {
        console.error('上传失败：', error)
        ElMessage.error('上传失败：' + error.message)
    }
}

// 格式化日期
const formatDateTime = (dateStr) => {
    if (!dateStr) return '--'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    })
}

// 获取状态样式
const getStatusType = (status) => {
    const statusMap = {
        0: 'info',  
        1: 'success',
        2: 'danger'
        
    }
    return statusMap[status] || 'info'
}

const getStatusText = (status) => {
    const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '未通过'
    }
    return statusMap[status] || status
}
const getInterviewStatusType = (status) => {
    const statusMap = {
        0: 'info',  
        1: 'success' ,
        2: 'info',
        3: 'danger'
        
    }
    return statusMap[status] || 'info'
}
const getInterviewStatusText = (status) => {
    const statusMap = {
        0: '待面试',
        1: '通过面试',
        2: '待定',
        3: '未通过面试'
    }
    return statusMap[status] || status
}
onMounted(() => {
    loadUserInfo()
    loadApplication()
    loadInterviews()
})
</script>

<style scoped>
.personal-container {
    min-height: 100vh;
    background-color: #f5f7fa;
}

.header {
    background-color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
    max-width: 1200px;
    margin: 0 auto;
    height: 60px;
    display: flex;
    align-items: center;
}

.logo {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
}

.logo-img {
    height: 36px;
}

.company-name {
    font-size: 24px;
    font-weight: bold;
    background: linear-gradient(45deg, #409eff, #36d1dc);
    -webkit-background-clip: text;
    color: transparent;
}

.main-content {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 20px;
}

.user-card {
    text-align: center;
    padding: 20px;
}

.user-info {
    margin-bottom: 20px;
}

.user-info h3 {
    margin: 10px 0 5px;
    color: #303133;
}

.email {
    color: #909399;
    font-size: 14px;
}

.menu-list {
    text-align: left;
}

.menu-item {
    padding: 12px 20px;
    margin: 4px 0;
    cursor: pointer;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;
}

.menu-item:hover {
    background-color: #f5f7fa;
}

.menu-item.active {
    background-color: #ecf5ff;
    color: #409eff;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.avatar-uploader {
    text-align: center;
    cursor: pointer;
}

.avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;  /* 确保图片正确填充 */
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
}

.avatar-uploader:hover .avatar-uploader-icon {
    border-color: #409EFF;
    color: #409EFF;
}

.security-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0;
}

.security-info h4 {
    margin: 0 0 8px;
    color: #303133;
}

.security-info p {
    margin: 0;
    color: #909399;
    font-size: 14px;
}
</style>